<template>
    <!--消耗分摊修改 -->
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="分摊明细"
                    name="receivingMaterials"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <BillTop title="消耗分摊编辑" @cancel="cancel"></BillTop>
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="basicFormData"
                                        label-width="150px"
                                         ref="ruleForm"
                                        :rules="rules"
                                        class="demo-ruleForm"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="消耗分摊编号："
                                                >
                                                    {{ basicFormData.billNo }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="所属机构："
                                                >
                                                    {{ basicFormData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="分包商："
                                                    prop="subcontractorName"
                                                >
                                                    <el-input
                                                        v-model="
                                                            basicFormData.subcontractorName
                                                        "
                                                         v-if="basicFormData.redBillState !='3' "
                                                    >
                                                    </el-input>
                                                     <span  v-else>{{basicFormData.subcontractorName}}</span>
                                                    <el-button
                                                     v-if="basicFormData.redBillState !='3' "
                                                        type="primary"
                                                        style="
                                                            background: #2e61d7;
                                                            margin-left: 5px;
                                                        "
                                                        @click="selectSub"
                                                        >选择</el-button
                                                    >
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="分摊日期："
                                                    prop="allocationDate"
                                                >
                                                    <el-date-picker
                                                    v-if="basicFormData.redBillState !='3' "
                                                        v-model="
                                                            basicFormData.allocationDate
                                                        "
                                                        type="date"
                                                        placeholder="选择日期"
                                                        value-format="yyyy-MM-dd"
                                                        :clearable="false"
                                                    >
                                                    </el-date-picker>
                                                     <span  v-else>{{basicFormData.allocationDate}}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="状态：">
                                                    {{
                                                        [
                                                            '草稿',
                                                            '审核中',
                                                            '已审核',
                                                            '已关闭',
                                                            '已作废'
                                                        ][basicFormData.state]
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="录入人：">
                                                    {{
                                                        basicFormData.recorderName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-form-item label="备注：">
                                                <el-input
                                                    type="textarea"
                                                    :rows="2"
                                                    placeholder="请输入内容"
                                                    v-model="
                                                        basicFormData.remarks
                                                    "
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-row>
                                         <el-row>
                          <!-- 发生冲红单业务时，才显示 -->
                            <el-form-item label="冲红单：" v-if="basicFormData.redBillId != '' &&basicFormData.redBillNo != '' &&basicFormData.redBillState != ''">
                                  <span
                                      :style="
                                          redBillStateStyle
                                      "
                                      >{{
                                          redBillStateFun
                                      }}</span
                                  >
                              </el-form-item>
                      </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>

                        <!-- ------------------------------------------------------------------------------------- -->
                    </div>

                    <!-- 分摊明细 -->
                    <div id="receivingMaterialsCon" class="con">
                        <div class="tabs-title" id="receivingMaterials">
                            分摊明细
                        </div>
                        <!-- 当前未分摊物资 -->
                        <div class="e-table">
                            <div style="margin-bottom: 10px">
                                <span>当前待分摊物资：</span>
                            </div>
                            <el-table
                                class="table"
                                :data="notPortionmentList"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                @row-click="rowClick"
                                :max-height="$store.state.tableHeight"
                                ref="table"
                                v-sortTable="{ 'tableData': notPortionmentList, '_this': this, 'ref': 'table' }"
                            >

                                <el-table-column
                                    fixed
                                    type="index"
                                    label="序号"
                                    width="80"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    min-width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="单位"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="subItemName"
                                    label="分部分项"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="consumePrice"
                                    label="单价"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="consumeQuantity"
                                    label="消耗数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="consumeAmount"
                                    label="消耗金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="apportionedQuantity"
                                    label="已分摊数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="apportionedAmount"
                                    label="已分摊金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unapportionedQuantity"
                                    label="剩余数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unapportionedAmount"
                                    label="剩余金额"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>

                        <!--当前已选择物资  -->
                        <div class="e-table">
                            <div style="margin-bottom: 10px">
                                <span>当前已选择物资：</span>
                                <div class="top" style="margin-top: 10px">
                                    <div class="left" v-if="basicFormData.redBillState != '3'">
                                        <div>
                                           <el-button type="primary" style="background: #2e61d7"
                                           @click="selectContract"
                                                >选择合同</el-button
                                            >
                                        </div>
                                    </div>
                                </div>
                            </div>
                             <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span v-for="(item, index) in errorMsg" :key="index">
                                {{ item }}
                                </span>
                            </div>
                            <!-- {{consumeapportionmentList}} -->
                            <el-table
                                class="table"
                                :data="consumeapportionmentList"
                                border
                                style="width: 100%"
                                :row-class-name="tableRowClassName"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                @select="selectCheckbox"
                                :max-height="$store.state.tableHeight"
                                ref="table"
                                v-sortTable="{ 'tableData': consumeapportionmentList, '_this': this, 'ref': 'table' }"
                            >
                            <el-table-column type="selection" width="55">
                             </el-table-column>

                                <el-table-column
                                    fixed
                                    type="index"
                                    label="序号"
                                    width="80"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column fixed label="操作" width="70" v-if="basicFormData.redBillState != '3'">
                                    <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div style="cursor: pointer">
                                                <img
                                                    src="@/assets/btn/delete.png"
                                                    @click="
                                                        deleteEle(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                    v-if="$index > 0"
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="物资类别"
                                    min-width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    min-width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="单位"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="subItemName"
                                    label="分部分项"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价"
                                    width="100"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="consumeQuantity"
                                    label="消耗数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="consumeAmount"
                                    label="消耗金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="contractName"
                                    label="分包商合同名称"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="apportionedQuantity"
                                    label="分摊数量"
                                    width="130"
                                >
                                <template slot-scope="{ row,$index  }">
                                      <el-input
                                        v-enter-float="{
                                            set: row,
                                            key: 'apportionedQuantity'
                                        }"

                                        @input="input(row)"
                                        v-model="row.apportionedQuantity"
                                          v-if="$index > 0 &&basicFormData.redBillState != '3'"
                                        clearable
                                      ></el-input>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="apportionedAmount"
                                    label="分摊金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="designQuantity"
                                    label="设计（甲供）数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="designAmount"
                                    label="设计（甲供）金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="aSupplyQuantityExceed"
                                    label="超甲供数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="aSupplyAmountExceed"
                                    label="超甲供金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="nonASupplyQuantityExceed"
                                    label="非甲供数量"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="nonASupplyAmountExceed"
                                    label="非甲供金额"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="totalDeductionPayable"
                                    label="应扣款合计"
                                    width="130"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="aSupplyType"
                                    label="甲供料类型"
                                    width="130"
                                >
                                 <template slot-scope="{ row,$index  }">
                                    <el-select v-model="row.aSupplyType" placeholder="请选择" v-if="$index > 0 &&basicFormData.redBillState != '3'">
                                        <el-option
                                          v-for="item in procurementMethod"
                                          :key="item.value"
                                          :label="item.label"
                                          :value="item.value">
                                        </el-option>
                                  </el-select>
                                  <span v-else>{{['工程消耗','安全环保支出','研发支出'][row.aSupplyType]}}</span>
                                  </template>
                                </el-table-column>
                                <el-table-column
                                    prop="consumeType"
                                    label="消耗类型"
                                    width="130"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="material"
                            v-if="objFlag.flag5"
                        />
                        <div class="seize-a-seat" v-else>
                            <i class="el-icon-loading"></i>
                        </div>
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :tableData.sync="auditHistoryTable"
                                @getAuditHistory="getAuditHistory"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
           <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

            <!-- <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                >保存</el-button
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="submit()"
                >保存并提交</el-button
            >
             <el-button
        type="primary"
        style="background: #2e61d7"
        @click="undoAudit"
        v-if="basicFormData.state === '1'"
        v-debounce
        >撤回</el-button
      >
             <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          >
            <el-button type="danger" size="small" @click="ctDelete"  v-if="basicFormData.state === '0'"
                >删除</el-button
            > -->
            <el-button @click="cancel()">关闭</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import CommonApi from '@/api/materials/common.js'
import Api from '@/api/materials/consumeapportionment.js'
import {   getUuid, selectDataClient, openAppClient } from '@/utils/common'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            notPortionmentList: [], //未分摊物资
            consumeapportionmentList: [], //已选择物资
            auditHistoryTable: [], //审核历史
            value: '',
            textarea: '',
            formData: {},
            auditState: {}, //按钮状态
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'allocationDate': '',
                'billId': '',
                'billNo': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isRed': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'recorderId': '',
                'recorderName': '',
                'redBillId': '',
                'redBillNo': '',
                'redBillState': '',
                'remarks': '',
                'sourceId': '',
                'sourceNumber': '',
                'state': '',
                'subcontractorId': '',
                'subcontractorName': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            procurementMethod: [{
                value: 0,
                label: '工程消耗'
            }, {
                value: 1,
                label: '安全环保支出'
            }, {
                value: 2,
                label: '研发支出'
            }],
            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            orgIds: '',
            //验证
            rules: {

                allocationDate: [
                    {  required: true, message: '请选择分摊日期', trigger: 'change' }
                ],

            },
            redBillStateStyle: {
                width: '300px',
                height: '30px',
                color: '#fff',
                backgroundColor: '',
                'text-align': 'center'
            },
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1028', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId, //单据机构Id
                orgName: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName, //单据机构名称
                userId: localStorage.getItem('userId'), //审核人Id    ***
                workId: '', //流程Id
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1028,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
        }
    },
    computed: {

        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
        // 红单状态
        redBillStateFun () {
            let redState = ''
            switch (this.basicFormData.redBillState) {
            case '0':
                redState = '冲销中'
                break
            case '1':
                redState = '冲销中'
                break
            case '2':
                redState = '已冲销'
                break
            case '3':
                redState = '红单'
                break
            }
            return redState
        }
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.founderId = localStorage.getItem('userId')
        this.orgName = data.userInfo.orgInfo.orgName
        this.userId = localStorage.getItem('userId')
        this.billid = this.$route.query.billid
        this.getBasicData() //进入页面就获取基本信息数据
        this.getBasicDataList()
        this.getAttach()
        this.getCurrentUnitInfo()
        // this.aaa()
        //this.getData()
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
        'basicFormData.redBillState' () {
            if (this.basicFormData.redBillState == '3') {
                this.redBillStateStyle.backgroundColor = '#FF2300'
            } else if (
                this.basicFormData.redBillState == '0' ||
                this.basicFormData.redBillState == '1'
            ) {
                this.redBillStateStyle.backgroundColor = '#FFA40D'
            } else if (this.basicFormData.redBillState == '2') {
                this.redBillStateStyle.backgroundColor = 'rgb(153,153,153)'
            }
        }
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'receivingMaterials', 'accessory', 'auditHistory']
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),

        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1028,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.cancel, null, this.cancel)
                })
            })
        },
        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1028', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            CommonApi.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.cancel, null, this.cancel)
            })
        },
        //选择分包商
        selectSub () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/consume/listSubcontractorInfoForSelect', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择分包商' // 标题
            }).then(val => {
                this.setSelectedInfo(val)

                val.forEach(item=>{
                    this.basicFormData.subcontractorId = item.subcontractorId
                    this.basicFormData.subcontractorName = item.subcontractorName
                    this.getData(item.subcontractorId)
                })

            })
        },
        getData (id) {
            this.$Ajax
                .httpGet({
                    url: '/material/consume/listAllocableMaterialsforSelect',
                    params: {
                        orgId: this.orgId,
                        subcontractorId: id,
                    },
                })
                .then(res => {
                    const mapObj = {}
                    let arr = []
                    res.forEach(e => {
                        const children = []
                        e.materialClassNameArr = e.materialClassName.split('/')
                        e.materialClassIdArr = e.materialClassId.split('/')
                        // TODO: 统计小计
                        let obj
                        const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                        const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                        if (!mapObj[topClassId]) {
                            obj = {
                                topClassId,
                                topClassName,
                                customId: topClassId,
                                materialClassId: topClassId,
                                materialClassName: topClassName,
                                uuid: getUuid(),
                                totalAmount: '',
                                totalQuantity: '',
                            }
                            //这里需要改成push多个对象   还没改
                            arr.push(obj)

                            mapObj[topClassId] = obj
                        } else {
                            obj = mapObj[topClassId]
                        }

                        // 物资名称
                        children.push({
                            uuid: getUuid(),
                            customId: getUuid(),
                            topClassId,
                            topClassName,
                            apportionedAmount: e.apportionedAmount, //	已分摊金额
                            apportionedQuantity: e.apportionedQuantity, //	已分摊数量
                            consumeAmount: e.consumeAmount, //	消耗金额(元)
                            consumePrice: e.consumePrice, //	单价
                            consumeQuantity: e.consumeQuantity, //	消耗数量
                            materialClassId: e.materialClassIdArr.join('/'), //	物资类别id(1级类别id/2级类别id/..)
                            materialClassName: e.materialClassNameArr.join('/'), //	物资类别名称(1级类别名称/2级类别名称/..)
                            materialId: e.materialId, //	物资id
                            materialName: e.materialName, //	物资名称
                            spec: e.spec, //	规格型号
                            subItemId: e.subItemId, //结构部位id
                            subItemName: e.subItemName, //	结构部位名称
                            texture: e.texture, //	材质
                            unapportionedAmount: e.unapportionedAmount, //	剩余金额
                            unapportionedQuantity: e.unapportionedQuantity, //	剩余数量
                            unit: e.unit, //	计量单位
                            warehouseId: e.warehouseId, //	仓库id
                            warehouseName: e.warehouseName, //仓库名称
                        })
                        obj.children = !obj.children
                            ? children
                            : obj.children.concat(children)
                            // 统计小计
                        const count = obj.children.reduce(
                            (prev, c) => (prev += c.apportionedAmount || 0),
                            0
                        )
                        obj.materialName = `小计： ${count}`
                        obj.children = this.uniqueArray(obj.children, 'customId')
                    })
                    this.notPortionmentList = arr

                })
        },
        //点击待分摊表格的某行数据,同时给已选表格添加此行
        rowClick (row, column, event) {
            console.log('row', row)
            console.log('column', column)
            console.log('event', event)
            const mapObj = {}
            let arr = []
            let obj
            const children = []
            const topClassId = row.topClassId
            const topClassName = row.topClassName

            if (!mapObj[topClassId]) {
                obj = {
                    topClassId,
                    topClassName,
                    customId: topClassId,
                    materialClassId: row.topClassId,
                    materialClassName: row.topClassName,
                    uuid: getUuid(),
                    totalAmount: '',
                    totalQuantity: '',
                }
                //这里需要改成push多个对象   还没改
                arr.push(obj)

                mapObj[topClassId] = obj
            } else {
                obj = mapObj[topClassId]
            }
            // 物资名称
            children.push({
                uuid: getUuid(),
                customId: getUuid(),
                apportionedAmount: row.apportionedAmount, //	已分摊金额
                apportionedQuantity: row.apportionedQuantity, //	已分摊数量
                aSupplyQuantityExceed: 0, //超甲供数量
                aSupplyAmountExceed: 0, //"超甲供金额
                aSupplyType: null, //甲供料类型
                billId: this.billid, //	消耗分摊id
                changeType: 1, //	变更类型
                consumeAmount: row.consumeAmount, //	消耗金额
                consumeQuantity: row.consumeQuantity, //消耗数量
                SubcontractName: '', // 分包商合同名称
                consumeType: null, //消耗类型
                contractId: '', //	合同id
                contractName: '', //	合同名称
                designAmount: 0, //	设计(甲供)金额
                designQuantity: 0, //	设计(甲供)数量
                dtlId: '', //消耗分摊明细id
                topClassId: topClassId,
                materialClassId: row.materialClassId, //	物资类别id(1级类别id/2级类别id/..)
                materialClassName: row.materialClassName, //	物资类别名称(1级类别名称/2级类别名称/..)
                materialId: row.materialId, //	物资id
                materialName: row.materialName, //	物资名称
                nonASupplyAmountExceed: 0, //	超非甲供金额
                nonASupplyQuantityExceed: 0, //	超非甲供数量
                price: row.consumePrice, //	单价
                spec: row.spec, //	规格型号
                subItemId: row.subItemId, //	结构部位id
                subItemName: row.subItemName, //	结构部位名称
                texture: row.texture, //	材质
                totalDeductionPayable: 0, //	应扣款合计
                unit: row.unit, //	计量单位
                warehouseId: row.warehouseId, //	仓库id
                warehouseName: row.warehouseName, //	仓库名称
                // 'apportionedAmount': 33,
                // 'apportionedQuantity': 22,
                // 'aSupplyQuantityExceed': 22,
                // 'aSupplyAmountExceed': 22,
                // 'aSupplyType': 1,
                // 'billId': '1524938112618917890',
                // 'changeType': 1,
                // 'consumeAmount': 11,
                // 'consumeQuantity': 11,
                // 'SubcontractName': '',
                // 'consumeType': null,
                // 'contractId': '1526127769444638722',
                // 'contractName': '物资分摊专用合同1',
                // 'designAmount': 22,
                // 'designQuantity': 22,
                // 'dtlId': '',
                // 'materialClassId': '1500729232783503361/1500729509653704706',
                // 'materialClassName': '建筑钢材/一级钢材',
                // 'materialId': '1492034311182880769',
                // 'materialName': '钢材0001',
                // 'nonASupplyAmountExceed': 22,
                // 'nonASupplyQuantityExceed': 22,
                // 'price': 1,
                // 'spec': '规格1',
                // 'subItemId': '',
                // 'subItemName': '',
                // 'texture': '测试材质001',
                // 'totalDeductionPayable': 44,
                // 'unit': 'T',
                // 'warehouseId': '1524666021487243266',
                // 'warehouseName': '分包商111'
            })
            obj.children = !obj.children
                ? children
                : obj.children.concat(children)
            // 统计小计
            const count = obj.children.reduce(
                (prev, c) => (prev += c.apportionedAmount || 0),
                0
            )
            obj.materialName = `小计： ${count}`
            obj.children = this.uniqueArray(obj.children, 'customId')
            this.consumeapportionmentList = arr
        },
        //选择合同
        selectContract () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getConsumptionAllocation', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify(
                    {
                        'orgId': this.orgId,
                        'subcontractorId': this.basicFormData.subcontractorId
                    }
                ),
                Title: '选择合同' // 标题
            }).then(val => {
                this.setSelectedInfo(val)

                // this.contractName =   val[0].contractName  //分包商合同名称
                // this.ContractData()
                val.forEach(item=>{
                    this.consumeapportionmentList.forEach(a=>{
                        a.children.forEach(b=>{
                            b.contractId = item.contractId
                            b.contractName = item.contractName
                        })
                    })
                })
            })
        },

        //已选表格  勾选行
        selectCheckbox (selection, row) {
            console.log('selection', selection)
            console.log('row', row)
            let params = []
            const obj = {
                'contractId': row.contractId, //合同Id  1526127769444638722  row.contractId
                'materialTypeId': `${row.topClassId}/${row.materialClassId}`,  //物资类别id    row.materialClassId
                'supplyType': row.aSupplyType //甲供类型 1、工程消耗 2、研发支出 3、安全环保支出  row.aSupplyType
            }
            params.push(obj)
            //接口获取合同数据
            this.$Ajax
                .httpPost({
                    url: '/subcontract/thirdParty/getConsumptionAllocationDetailed',
                    params,
                }).then(res=>{
                    res.forEach(item=>{
                        this.consumeapportionmentList.forEach(a=>{
                            a.children.forEach(b=>{
                                console.log('b', b)
                                console.log('item', item)
                                b.materialClassId = `${a.topClassId}/${b.materialClassId}`
                                if(b.contractId == item.contractId && b.materialClassId == item.materialTypeId && b.aSupplyType == item.supplyType) {
                                    b.designAmount =  item.amount//设计（甲供）金额
                                    b.designQuantity = item.quantity//设计（甲供）数量
                                    // 计算：超甲供数量   超甲供金额  分摊数量-甲供数量。未超甲供时，则显示为0  分摊金额-甲供金额.。未超甲供时，则显示为0
                                    if(b.apportionedQuantity > b.designQuantity) {
                                        b.aSupplyQuantityExceed =  b.apportionedQuantity - b.designQuantity
                                    }else{
                                        b.asupplyQuantityExceed = 0
                                    }

                                    if(b.apportionedAmount > b.designAmount) {
                                        b.asupplyAmountExceed = b.apportionedAmount - b.designAmount
                                    }else{
                                        b.asupplyAmountExceed = 0
                                    }
                                    //如果甲供为0  非甲供数量 = 分摊数量   非甲供金额 = 分摊金额
                                    if(b.designAmount === 0) {
                                        b.nonASupplyAmountExceed = b.apportionedQuantity
                                    }
                                    if(b.designQuantity === 0) {
                                        b.nonASupplyQuantityExceed = b.apportionedAmount
                                    }
                                    //计算 应扣款合计  totalDeductionPayable   超甲供+非甲供
                                    b.totalDeductionPayable = b.asupplyAmountExceed + b.nonASupplyAmountExceed

                                }
                            })
                        })
                    })
                })
        },
        aaa () {

            this.consumeapportionmentList = [
                { 'topClassId': '1500727756765982722',
                    'topClassName': '主要材料',
                    'customId': '1500727756765982722',
                    'materialClassId': '1500727756765982722',
                    'materialClassName': '主要材料',
                    'uuid': '2D57F849-C116-4EC4-B63E-8C51E39837BA',
                    'totalAmount': '',
                    'totalQuantity': '',
                    'children': [
                        { 'uuid': 'D97D30B5-4207-4555-88B4-F23E46D30861',
                            'customId': 'BE46559E-38F6-4C24-A458-DBB076112331',
                            'apportionedAmount': 33,
                            'apportionedQuantity': 22,
                            'aSupplyQuantityExceed': 22,
                            'aSupplyAmountExceed': 22,
                            'aSupplyType': 1,
                            'billId': '1524938112618917890',
                            'changeType': 1,
                            'consumeAmount': 11,
                            'consumeQuantity': 11,
                            'SubcontractName': '',
                            'consumeType': null,
                            'contractId': '1526127769444638722',
                            'contractName': '物资分摊专用合同1',
                            'designAmount': 22,
                            'designQuantity': 22,
                            'dtlId': '',
                            'materialClassId': '1500729232783503361/1500729509653704706',
                            'materialClassName': '建筑钢材/一级钢材',
                            'materialId': '1492034311182880769',
                            'materialName': '钢材0001',
                            'nonASupplyAmountExceed': 22,
                            'nonASupplyQuantityExceed': 22,
                            'price': 1,
                            'spec': '规格1',
                            'subItemId': '',
                            'subItemName': '',
                            'texture': '测试材质001',
                            'totalDeductionPayable': '',
                            'unit': 'T',
                            'warehouseId': '1524666021487243266',
                            'warehouseName': '分包商111' }
                    ], 'materialName': '小计： 0' }
            ]
            console.log('1111', this.consumeapportionmentList)
        },

        //保存
        save () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.$router.go(0))
                })
                .catch(() => {
                    this.scorllError()
                })
        },

        //保存并提交
        submit () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    CommonApi.AuditCommit(this.auditParams).then(() => {
                        this.clientPop('suc', '保存并提交成功', this.cancel, null, this.cancel)
                    })
                })
                .catch(() => {
                    this.scorllError()
                })

        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        Api.Editconsumeapportionment(this.basicFormData)
                            .then(() => {
                                this.getBasicData() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },

        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        Api.EditconsumeapportionmentList(this.consumeapportionmentList)
                            .then(() => {
                                this.getBasicDataList() //更新明细
                                resolve()
                            })
                            .catch(err => {
                                this.setError('receivingMaterials')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('receivingMaterials')
                        reject(err)
                    })
            })
        },
        //根据消耗盘点id查询消耗盘点基础信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/consumptionAllocation/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //根据消耗盘点id获取消耗盘点明细信息
        getBasicDataList () {
            this.$Ajax
                .httpGet({
                    url: '/material/consumptionAllocation/getListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res=>{
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.apportionedAmount || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })
                    this.consumeapportionmentList = res

                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1028',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: '',
            }
            CommonApi.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                // if(this.notPortionmentList.length === 0) {
                //     let str = '分摊明细不能为空！'
                //     this.errorMsg.push(str)
                // }
                // else  if (this.notPortionmentList.length > 0) {
                //     this.notPortionmentList.forEach(v => {
                //         v.children.forEach((item, index) => {
                //             if (item.changeType !== -1) {
                //                 if (item.apportionedQuantity === '' || item.apportionedQuantity === null) {
                //                     let str = `请填写第 ${index + 1} 行的分摊数量`
                //                     this.errorMsg.push(str)
                //                 }
                //                 if (item.aSupplyType === '' || item.aSupplyType === null) {
                //                     let str = `请选择第 ${index + 1} 行的发料类型`
                //                     this.errorMsg.push(str)
                //                 }

                //             }
                //         })
                //     })
                // }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        //删除物资明细
        deleteEle (row) {
            row.changeType = -1
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else {
                row.changeType = 2
            }
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/consumptionAllocation/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel, null, this.cancel)
                    }
                })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./consumeapportionment')
        },

        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
